package com.ds.lens.manager.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

@Component
@Slf4j
public class ShellUtil {

    public  int executeShell(String[] shellCommand) throws IOException {
        int success = 1;
        StringBuffer stringBuffer = new StringBuffer();
        StringBuffer errorBuffer = new StringBuffer();
        BufferedReader bufferedReader = null;
        BufferedReader brErrorReader = null;
        //格式化日期时间，记录日志时使用
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS ");

        try {
            stringBuffer.append(dateFormat.format(new Date())).append("准备执行Shell命令 ").append(Arrays.toString(shellCommand)).append(" \r\n");

            Process pid = null;
//            String[] cmd = {"/bin/sh", "-c", shellCommand};
            //执行Shell命令
            pid = Runtime.getRuntime().exec(shellCommand);




            if (pid != null) {
                stringBuffer.append("进程号：").append(pid.toString()).append("\r\n");
                //bufferedReader用于读取Shell的输出内容
                bufferedReader = new BufferedReader(new InputStreamReader(pid.getInputStream()), 1024);

                //读取标准错误流
                brErrorReader = new BufferedReader(new InputStreamReader(pid.getErrorStream()), 1024);

                pid.waitFor();

            } else {
                stringBuffer.append("没有pid\r\n");
            }
            stringBuffer.append(dateFormat.format(new Date())).append("Shell命令执行完毕\r\n执行结果为：\r\n");
            String line = null;
            //读取Shell的输出内容，并添加到stringBuffer中
            while (bufferedReader != null && (line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line).append("\r\n");
            }

            String errline = null;
            while (brErrorReader != null && (errline = brErrorReader.readLine()) != null) {
                errorBuffer.append(errline).append("\r\n");
            }

        } catch (Exception ioe) {
            stringBuffer.append("执行Shell命令时发生异常：\r\n").append(ioe.getMessage()).append("\r\n");
        } finally {
            if (bufferedReader != null) {
                    bufferedReader.close();

            }
            if (brErrorReader != null) {
                brErrorReader.close();

            }
            log.info(stringBuffer.toString());
            log.info(errorBuffer.toString());

            success = 0;
        }
        return success;
    }

    public static void main(String[] args) throws IOException {



    }

}
